<?php
class C_InstantMessage extends Controller {
	var $template_mod;
	var $_db;
	var $join_db;
	var $limit = 50;
	var $my_user_id; 
	
	function C_InstantMessage($template_mod = "general") {
		parent::Controller();
		$this->template_mod = $template_mod;
		$this->_db = $GLOBALS['frame']['adodb']['db']; 	
		$this->my_user_id = $this->_me->get_id();
	}

	public function actionViewMessages(){		
		$obj = Celini::newORDO('InstantMessage');
		$this->view->assign('newMessages', $obj->getNewMessageNumber($this->my_user_id));
		$this->view->assign('path', Utils::getAppUrl() . "/user/user_photo/");
		return $this->view->render("view_messages.html");
	}
	
	public function actionGetMessages(){
		$obj = Celini::newORDO('InstantMessage');
		//TODO @Localization
		if ($_GET['whichbox'] == 'outbox') {
			$messages = $obj->getAllMessagesOutbox($this->my_user_id);
			//@localization
			$title = L10nHelper::_("Outbox");
		} else {
			$messages = $obj->getAllMessagesInbox($this->my_user_id);
			//@localization
			$title = L10nHelper::_('Inbox');
		}
		return $this->buildMessagesBox($messages, $_GET['whichbox'], $title);
	}
	
	public function actionGetFavourite() {
		$obj = Celini::newORDO('InstantMessage');
		$this->view->assign_by_ref('users', $obj->getAllUserImages());
		$this->view->assign_by_ref('fMaps', $obj->getFavouriteMap($this->my_user_id));
		$this->view->assign('path', Utils::getAppUrl() . "/user/user_photo/");
		return $this->view->render("favourite.html");
	}
	
	public function actionGetFavouriteToAdd() {
		$obj = Celini::newORDO('InstantMessage');
		$this->view->assign_by_ref('fMaps', $obj->getFavouriteMap($this->my_user_id));
		$this->view->assign('path', Utils::getAppUrl() . "/user/user_photo/");
		return $this->view->render("new_message_favourite.html");
	}
	
	public function actionDeleteMessages(){
		$obj = Celini::newORDO('InstantMessage');
		if ($_GET['whichbox'] == "inbox") {
			foreach ($_GET['deleted'] as $message) {
				$obj->deleteInboxMessage($message);
			}
		} elseif ($_GET['whichbox'] == "outbox") {
			foreach ($_GET['deleted'] as $message) {
				$obj->deleteOutboxMessage($message);
			}			
			
		}	
		return json_encode($_GET['deleted']);
	}

	public function actionSendMessage(){
		$recipients = explode(';', str_replace(' ', '', $_POST['recipientList']));
		$user = Celini::newORDO('User');
		foreach ($recipients as $recipient){		
			if ($recipient != ''){		
				$recipientId = $user->getUserID($recipient);
				Celini::newORDO('InstantMessage')->addNewInstantMessage($_POST['message'], 
					$this->my_user_id, $recipientId, $_POST['emergency']);
			}
		}
		return L10nHelper::_("The message was sent successful!");
	}
	
	public function actionReplyMessage() {
		$recipientId = Celini::newORDO('User')->getUserID($_POST['recipient']);
		return Celini::newORDO('InstantMessage')->addNewInstantMessage($_POST['message'], 
			$this->my_user_id, $recipientId, $_POST['emergency'], $_POST['rootId']);
	}
	
	public function actionGetNewMessageAlert(){		
		$response['value'] = '0';
		$newMsg = Celini::newORDO('InstantMessage')->getNewestMessage($this->my_user_id);
		return json_encode($newMsg);
	}
	
	public function actionGetNumOfNewMessages() {
		return Celini::newORDO('InstantMessage')->getNewMessageNumber($this->my_user_id);	
	}
	
	public function actionCheckRecipients() {
		$recipients = explode(';', str_replace(' ', '', $_POST['recipients']));
		$response = "User ";
		foreach ($recipients as $recipient){
			if ($recipient != ''){
				//TODO @Localization
				$obj = Celini::newORDO('User');			
				$id = $obj->getUserID($recipient);
				if ($id == "not exist"){
					return $recipient;
				}
			}
		}
		return "OK";
	}
	
	public function actionGetAllUsernames(){
		$obj = Celini::newORDO('User');
		$q = strtolower($_GET['q']);
		if (!$q) return;
		$usernames = $obj->getAllUsernames($q);
		foreach ($usernames as $value) {
			echo $value['username'] . "\n";
		}		
	}
		
	public function actionRedirectToMessagePage() {
		header("Location: ".Celini::link('viewMessages','InstantMessage'));
	}
	
	public function actionMarkAsRead() {
		Celini::newORDO('InstantMessage')->markAsRead($_GET['messageId']);
		return 1;
	}
	
	public function actionUpdateFavouriteMap() {
		$fMap = Celini::newORDO('MsgFavouriteMap');
		if (!$fMap->checkExistingMap($this->my_user_id, $_GET['userId'])) {
			return $fMap->addNewMap($this->my_user_id, $_GET['userId']);
		}
		return -1;
	}
	
	public function actionDeleteFavouriteMap() {
		return Celini::newORDO('MsgFavouriteMap')->deleteMap($_GET['mappingId']);
	}
	
	public function actionViewConversation() {
		$this->view->assign_by_ref('conversation', Celini::newORDO('InstantMessage')->getConversationInbox($_GET['rootId']));
		$this->view->assign('myUserId', $this->my_user_id);
		$this->view->assign('currentMsg', $_GET['messageId']);
		$this->view->assign('username', $_GET['username']);
		return $this->view->render('view_conversation.html');
	}
	
	private function buildMessagesBox($messages, $whichbox, $title){
		//@localization
		$response = "<div class='documentListHeader' style='width: 835px; text-align: center; margin-top: 10px;'>
						<span style='text-transform: uppercase;'>$title</span>
					</div>
					<table class='grid' cellspacing='0' cellpadding='0' id='messages' style='margin-top: 2px'>
						<tr>
							<th style='padding-right: 5px; width: 20px; text-align: center;'><input type='checkbox' name='checkall' id='checkall'/></th>
							<th style='width: 20px'>&nbsp;</th>
							<th style='width: 20px'>&nbsp;</th>
							<th style='width: 500px'>".L10nHelper::_("Content")."</th>
							<th style='width: 100px'>".L10nHelper::_("Time")."</th>
							<th style='width: 48px'>&nbsp;</th>
						</tr>";
		foreach ($messages as $message){
			// If sender is set, get it else get recipient_id.
			$imgPath =  Utils::getAppUrl() . "/user/user_photo/" . $message['username'] . ".png";
			$emergency = '&nbsp;';
			if ($message['emergency'] > 0) {
				$emergency = "<img src='../images/warning.png'/>";
			}
			$status = '&nbsp;';
			if ($message['status'] == 'new' or $message['status'] == 'unread') {
				$status = "<img src='../images/new.png'/>";
			}	
			//@localization
			$response = $response. 
				"<tr id='{$message['message_id']}'>
					<td style='text-align: center'>
						<input type='checkbox' name='{$whichbox}_messages_deleted[]' value='{$message['message_id']}'>
					</td>
					<td style='text-align: center'>$emergency</td>
					<td style='text-align: center'>$status</td>			
					<td id='imgtip' style='text-align: left; cursor: pointer' onclick='viewMessage({$message['message_id']}, {$message['root']}, \"{$message['username']}\", \"$whichbox\")'>
						<span class='uName' style='color: green; font-size: 13px;'>{$message['username']}</span>
						<br/><span style='color: #444; padding-left: 10px'>{$this->snippet($message['message'])}</span>
						<img id='imgPath' style='display: none' src='$imgPath' />
					</td >
					<td>
						<span>{$message['date']}</span>
					</td>
					<td style='text-align: center'>
						<a class='{$whichbox}_reply' href='javascript:replyMessage({$message['root']}, \"{$message['username']}\", {$message['emergency']})'>
							<img src='../images/msg_reply.png'/>
						</a> &nbsp;
					</td>				
				</tr>";
		}
		$response .= "<tr><td style='border: none' colspan='6'><button id='newMessage' onclick=\"deleteMessages('$whichbox')\">".L10nHelper::_("Delete")."</button></td></tr>
					</table>";
		return $response;
	}
	
	private function snippet($msg,	$length = 85, $tail="...") {
		$text = trim($msg);
		$txtl = strlen($text);
		if($txtl > $length) {
			for($i = 1; $text[$length-$i] != " "; $i++) {
				if($i == $length) {
					return substr($text, 0, $length) . $tail;
				}
			}
			$text = substr($text, 0, $length-$i+1) . $tail;
		}
		return $text;
	}
}	
?>